package com.laowang.project.system.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.common.utils.StringUtils;
import com.laowang.common.utils.http.HttpClient;
import com.laowang.framework.security.LoginUser;
import com.laowang.framework.security.service.TokenService;
import com.laowang.project.pay.config.WeixinOpenNew;
import com.laowang.project.system.domain.WxUser;
import com.laowang.project.system.domain.vo.ZcRecordVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;

import org.springframework.web.bind.annotation.*;
import com.laowang.project.system.domain.ZcWxUser;
import com.laowang.project.system.service.ZcWxUserService;
import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;

/**
 * H5用户Controller
 *
 * @author laowang
 * @date 2025-09-09
 */
@Slf4j
@Api(tags = "众筹H5用户接口")
@RestController
@RequestMapping("/zcUser")
public class ZcWxUserController extends BaseController {
    @Autowired
    private ZcWxUserService zcWxUserService;

    @Autowired
    private TokenService tokenService;



    /**
     * 获取登录微信的二维码
     * 下面是要组装的url
     */
    @ApiOperation(value = "H5端 授权登录", notes = "")
    @GetMapping("/redirectUri")
    public AjaxResult getQrConnect() {
        // https://open.weixin.qq.com/connect/oauth2/authorize
        // https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=回调地址&response_type=code&scope=snsapi_login&state=随机数#wechat_redirect
        String baseUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
            "appid=%s" +
            "&redirect_uri=%s" +
            "&response_type=code&" +
            "scope=snsapi_userinfo&" +
            "state=%s" +
            "#wechat_redirect";

        //String appId = weixinOpen.getAppId();
        String appId = WeixinOpenNew.appId;
        // 将回调url转码
        try {
            //String redirectUri = weixinOpen.getRedirectUri();
            String redirectUri = "https://wx.hubeixiangxiang.com/zcweb/";
            redirectUri = URLEncoder.encode(redirectUri, "UTF-8");
            //生成随机数   要是这个服务做得有负载均衡就不行 可能我是第一个服务存的session 但是他回调我的第二个服务器 session 就不一样了  这里用到了spring session 来管理
            String state = UUID.randomUUID().toString();

            String qrurl = String.format(baseUrl, appId, redirectUri, state);
            return AjaxResult.success("操作成功", qrurl);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return AjaxResult.error("操作失败", e.getMessage());
        }

    }


    @ApiOperation(value = "接受code返回用户信息", notes = "接受code返回用户信息方法详情")
    @GetMapping("/code")
    public AjaxResult code(String code, Integer shareId/*,String phone,HttpSession httpSession*/ /*HttpSession httpSession,@RequestBody Map<String,String> map*/) {

        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        String baseUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
            "appid=%s" +
            "&secret=%s" +
            "&code=%s&" +
            "grant_type=authorization_code";
        //第二步：通过 code 获取 access_token
        String appid = WeixinOpenNew.appId;
        String secret = WeixinOpenNew.secret;
        //String code = map.get("code");
        String format = String.format(baseUrl, appid, secret, code);

        // 创建httpclient对象(模拟浏览器)
        HttpClient httpClient = new HttpClient(format);
        // 设置https 协议
        httpClient.setHttps(true);
        // 发送请求
        try {
            httpClient.post();
        } catch (IOException e) {
            log.error("httpclient方法异常get{}", e.getMessage());
            e.printStackTrace();
        }
        //得到返回结果
        String content = "";
        try {
            content = httpClient.getContent();
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map mapResult = JSONObject.parseObject(content, Map.class);

        System.out.println("map:" + mapResult);

        // 获取正确的返回结果信息
        String access_token = (String) mapResult.get("access_token");
        String openid = (String) mapResult.get("openid");// 这个是每一个微信的用户的唯一标识
        if  (StringUtils.isEmpty(openid)) {
            return AjaxResult.error(mapResult.toString());
        }
        // 获取用户个人信息（UnionID 机制） GET https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID

        String baseUrl1 = "https://api.weixin.qq.com/sns/userinfo?" +
            "access_token=%s" +
            "&openid=%s";
        String format1 = String.format(baseUrl1, access_token, openid);

        // 创建httpclient对象(模拟浏览器)
        HttpClient httpClient1 = new HttpClient(format1);
        // 设置https 协议
        httpClient1.setHttps(true);
        // 发送请求
        try {
            httpClient1.get();
        } catch (IOException e) {
            log.error("httpclient方法异常get{}", e.getMessage());
            e.printStackTrace();
        }
        String content1 = "";
        try {
            content1 = httpClient1.getContent();
        } catch (IOException e) {
            e.printStackTrace();
        }

        mapResult = JSONObject.parseObject(content1, Map.class);
        System.out.println("mapResult377:" + JSONObject.toJSONString(mapResult));
        String nickname = (String) mapResult.get("nickname");
        Integer sex = (Integer) mapResult.get("sex");
        String headimgurl = (String) mapResult.get("headimgurl");
        ZcWxUser zcWxUser = zcWxUserService.getByOpenid(openid);
        if (zcWxUser == null) {
            zcWxUser = new ZcWxUser();
            zcWxUser.setOpenid(openid);
            zcWxUser.setNickname(nickname);
            zcWxUser.setAvatar(headimgurl);
            zcWxUser.setGender(sex);
            if (shareId != null) {
                ZcWxUser zcWxUser1 = zcWxUserService.selectZcWxUserById(shareId);
                if (zcWxUser1 != null) {
                    zcWxUser.setIntroId(shareId);
                }
            }
            zcWxUserService.insertZcWxUser(zcWxUser);

        } else {

            if (shareId != null) {
                ZcWxUser wxUser1 = zcWxUserService.selectZcWxUserById(shareId);
                if (wxUser1 != null && zcWxUser.getIntroId() == null) {
                    zcWxUser.setIntroId(shareId);

                }
            }

            zcWxUser.setAvatar(headimgurl);
            zcWxUser.setNickname(nickname);
            zcWxUserService.updateZcWxUser(zcWxUser);
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUserType("zcUser");
        loginUser.setZcWxUser(zcWxUser);
        String token = tokenService.createToken(loginUser);

        return AjaxResult.success("操作成功", token);


    }


    /**
     * 根据token获取用户信息
     */
    @ApiOperation(value = "H5端 根据token获取众筹用户信息", notes = "")
    @GetMapping(value = "/userInfo")
    public AjaxResult getUserInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ZcWxUser zcWxUser = loginUser.getZcWxUser();

        return AjaxResult.success(zcWxUser);
    }

   /*
   *
    *    SELECT total_price,create_time,refund_time,`status` FROM zc_wx_order
        WHERE `status` in (1,2) and user_id =#{}
        ORDER BY create_time desc
    *
    * */

    @ApiOperation(value = "H5端 获取用户的众筹记录", notes = "")
    @GetMapping(value = "/getZcRecord")
    public AjaxResult getZcRecord() {
        Integer userId = SecurityUtils.getLoginUser().getZcWxUser().getId();
        ZcWxUser zcWxUser = zcWxUserService.selectZcWxUserById(userId);
        List<ZcRecordVo> list = zcWxUserService.getZcRecord(userId);
        BigDecimal total = BigDecimal.ZERO;
        for (ZcRecordVo zcRecordVo : list) {
            total =  total.add(zcRecordVo.getTotalPrice());
        }
        zcWxUser.setTotal(total);
        zcWxUser.setZcRecordVoList(list);
        return AjaxResult.success(zcWxUser);
    }

    /**
     * 查询H5用户列表
     */
    @ApiOperation(value = "查询H5用户列表", notes = "")
    @PreAuthorize("@ss.hasPermi('system:zcUser:list')")
    @GetMapping("/list")
    public TableDataInfo list(ZcWxUser zcWxUser) {
        startPage();
        List<ZcWxUser> list = zcWxUserService.selectZcWxUserList(zcWxUser);
        return getDataTable(list);
    }

    /**
     * 导出H5用户列表
     */
    @ApiOperation(value = "导出H5用户列表", notes = "")
    @PreAuthorize("@ss.hasPermi('system:zcUser:export')")
    @Log(title = "H5用户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ZcWxUser zcWxUser) {
        List<ZcWxUser> list = zcWxUserService.selectZcWxUserList(zcWxUser);
        ExcelUtil<ZcWxUser> util = new ExcelUtil<ZcWxUser>(ZcWxUser.class);
        return util.exportExcel(list, "zcUser");
    }

    /**
     * 获取H5用户详细信息
     */
    @ApiOperation(value = "获取H5用户详细信息", notes = "")
    @PreAuthorize("@ss.hasPermi('system:zcUser:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(zcWxUserService.selectZcWxUserById(id));
    }

    /**
     * 新增H5用户
     */
    @ApiOperation(value = "新增H5用户", notes = "")
    @PreAuthorize("@ss.hasPermi('system:zcUser:add')")
    @Log(title = "H5用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZcWxUser zcWxUser) {
        return toAjax(zcWxUserService.insertZcWxUser(zcWxUser));
    }

    /**
     * 修改H5用户
     */
    @ApiOperation(value = "修改H5用户", notes = "")
    @PreAuthorize("@ss.hasPermi('system:zcUser:edit')")
    @Log(title = "H5用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZcWxUser zcWxUser) {
        return toAjax(zcWxUserService.updateZcWxUser(zcWxUser));
    }

    /**
     * 删除H5用户
     */
    @ApiOperation(value = "删除H5用户", notes = "")
    @PreAuthorize("@ss.hasPermi('system:zcUser:remove')")
    @Log(title = "H5用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(zcWxUserService.deleteZcWxUserByIds(ids));
    }
}
